#include "qmlhandler.h"

QMLHandler::QMLHandler(QObject *parent) :
    QObject(parent)
{
}

QMLHandler::QMLHandler(Baza *database, QDeclarativeContext *ctxt, QApplication *app)
{
    this->database = database;
    this->ctxt = ctxt;
    this->app = app;

    chosenLanguageIndex=-1;
}

QMLHandler::~QMLHandler()
{}

bool QMLHandler::allLists_Add(QString name){
    if (database->postojiPopis(name) != -1){
        return false;
    }else{
        //promijenimo prioritete popisa na njihov redni broj u listi
        for(uint i = 0; i < listAllLists.size(); i++){
            Popis popis = listAllLists.at(i);
            database->postaviPrioritetPopis(popis.dajId(), i+1);
        }

        //dodamo novi popis s prioritetom 0
        database->dodajPopis(name);
        refreshAllLists();

        database->ispisiPopise();
        return true;
    }
}

void QMLHandler::allLists_Delete(int index){
    qDebug()<<"brisal bi na indexu "<<index;

    Popis popis = listAllLists.at(index);
    database->brisiPopis(popis.dajId());
    refreshAllLists();
}

void QMLHandler::allLists_MoveUp(int index)
{
    Popis popis_g = listAllLists.at(index-1);
    Popis popis_d = listAllLists.at(index);

    database->postaviPrioritetPopis(popis_g.dajId(), popis_d.dajPrioritetPopisa());
    database->postaviPrioritetPopis(popis_d.dajId(), popis_g.dajPrioritetPopisa());

    refreshAllLists();
}

void QMLHandler::allLists_MoveDown(int index)
{
    Popis popis_g = listAllLists.at(index);
    Popis popis_d = listAllLists.at(index+1);

    database->postaviPrioritetPopis(popis_g.dajId(), popis_d.dajPrioritetPopisa());
    database->postaviPrioritetPopis(popis_d.dajId(), popis_g.dajPrioritetPopisa());

    refreshAllLists();
}

void QMLHandler::allLists_Message(int popisIndex)
{
    int popisId = listAllLists.at(popisIndex).dajId();

    QString txt = "";
    QString tmp;
    int idn, ids = -1;
    std::vector<ElementPopisa> listaElementPopis = database->dajSveElementePopisa(popisId);

    for(uint k = 0; k < listaElementPopis.size(); k++)
    {
        ElementPopisa ep = listaElementPopis.at(k);
        idn = ep.dajArtikl().dajGrupu().dajId();
        if(k == 0)
        {
            txt += ep.dajArtikl().dajGrupu().dajImeGrupe().toUpper() + "\n";
            txt += ep.dajArtikl().dajImeArtikla().toLower() + " " + QString::number(ep.dajKolicinu(), 'g', 2);

            tmp = ep.dajMjernuJednincu();
            if(tmp == "kom") tmp = "x";

            txt += tmp + "\n";
        }
        else
        {
            if(idn == ids)
            {
                txt += ep.dajArtikl().dajImeArtikla().toLower() + " " + QString::number(ep.dajKolicinu(), 'g', 2);

                tmp = ep.dajMjernuJednincu();
                if(tmp == "kom") tmp = "x";

                txt += tmp + "\n";
            }
            else
            {
                txt += ep.dajArtikl().dajGrupu().dajImeGrupe().toUpper() + "\n";
                txt += ep.dajArtikl().dajImeArtikla().toLower() + " " + QString::number(ep.dajKolicinu(), 'g', 2);

                tmp = ep.dajMjernuJednincu();
                if(tmp == "kom") tmp = "x";

                txt += tmp + "\n";
            }
        }
        ids = idn;
    }

    QMessage msg;
    msg.setType(QMessage::Sms);
    msg.setBody(txt);

    QMessageService service;
    service.compose(msg);

}

bool QMLHandler::allLists_Rename(QString name, int index){
    if (database->postojiPopis(name) != -1){
        return false;
    }else{
        Popis popis = listAllLists.at(index);
        database->preimenujPopis(popis.dajId(), name);
        refreshAllLists();
        return true;
    }
}

void QMLHandler::allLists_DeleteBought(){
    for(uint i = 0; i < listAllLists.size(); i++)
    {
        Popis popis = listAllLists.at(i);
        if(!database->prazanPopis(popis.dajId()) && database->kupljenCijeliPopis(popis.dajId())){
            database->brisiPopis(popis.dajId());
            database->ispisiPopise();
            database->ispisiSveNaPopisima();
        }
    }
    refreshAllLists();
}

void QMLHandler::refreshAllLists()
{
    QString image;

    modelAllLists.clear();

    listAllLists=database->dajSvePopise();

    for(unsigned int i = 0; i < listAllLists.size(); i++)
    {
        Popis popis = listAllLists.at(i);

        if(database->dajSveElementePopisa(popis.dajId()).size() == 0)
        {
            image = "qrc:/images/prazno.png";
        }
        else if(database->kupljenCijeliPopis(popis.dajId()))
        {
            image = "qrc:/images/kupljeno.png";
        }
        else
        {
            image = "qrc:/images/puno.png";
        }
        modelAllLists.append(new ItemAllLists(popis.dajImePopisa(), image, i, popis.dajId()));
    }

    qDebug()<<"postavil model all lists!";
    ctxt->setContextProperty("modelAllLists", QVariant::fromValue(modelAllLists));
}

void QMLHandler::refreshLanguages(){
    modelLanguages.clear();

    std::vector<Jezik> listLanguages=database->dajSveJezike();

    for(unsigned int i = 0; i < listLanguages.size(); i++){
        Jezik jezik = listLanguages.at(i);

        if (jezik.jeOdabran())
            chosenLanguageIndex=i;

        modelLanguages.addLanguage(jezik);
    }

    ctxt->setContextProperty("modelLanguages", &modelLanguages);
}

void QMLHandler::settings_SetLanguage(int languageId){
    qDebug()<<"odabral !!"<<languageId;
    database->odaberiJezik(languageId);

    Jezik odabrani=database->dajOdabraniJezik();
    loadTranslation(odabrani.dajSifruJezika());

    refreshGroups();
}

int QMLHandler::getChosenLanguageIndex(){
    return chosenLanguageIndex;
}

void QMLHandler::loadTranslation(QString sifraJezika){
    translator.load("languages/translation/" + sifraJezika, ":/");

    app->installTranslator(&translator);
}

void QMLHandler::refreshGroups(){
    qDebug()<<"pozvan refreshgroups...";
    database->ispisiGrupe();

    modelGroups.clear();
    modelGroupsWithoutAllGroups.clear();

    std::vector<Grupa> listGroups=database->dajSveGrupe();

    Grupa allGroups=Grupa(-1, tr("All groups"), -1);

    modelGroups.addGroup(allGroups, 0);

    for(unsigned int i = 0; i < listGroups.size(); i++){
        Grupa group = listGroups.at(i);

        modelGroups.addGroup(group, i+1);
        modelGroupsWithoutAllGroups.addGroup(group, i);
    }

    ctxt->setContextProperty("modelGroups", &modelGroups);
    ctxt->setContextProperty("modelGroupsWithoutAllGroups", &modelGroupsWithoutAllGroups);
}


void QMLHandler::refreshItems(int groupId, int listIndex){
    database->ispisiArtikle();

    modelItems.clear();

    std::vector<Artikl> listItems=database->dajSveArtikle();

    int idProsleGrupe=-1;
    int idTrenutneGrupe;
    int rbrGrupe=0;
    int index=0;
    bool postojiNaPopisu=false;

    int listId=listIndex==-1?-1:listAllLists[listIndex].dajId();

    qDebug()<<"list id je "<<listId;

    for(unsigned int i = 0; i < listItems.size(); i++){
        Artikl item= listItems.at(i);

        postojiNaPopisu=listId==-1?false:database->postojiArtiklPopisId(item.dajId(), listId)>=0;

        idTrenutneGrupe=item.dajGrupu().dajId();

        bool dodaj=(groupId==-1||(groupId==idTrenutneGrupe));

        if (idTrenutneGrupe!=idProsleGrupe){
            rbrGrupe++;
            if (dodaj){
                modelItems.addItem(item, index, true, rbrGrupe);
                index++;
            }
            if (dodaj&&!postojiNaPopisu){
                modelItems.addItem(item, index, false, rbrGrupe);
                index++;
            }
            idProsleGrupe=idTrenutneGrupe;
        }
        else{
            if (dodaj&&!postojiNaPopisu){
                modelItems.addItem(item, index, false, rbrGrupe);
                index++;
            }
        }
    }

    ctxt->setContextProperty("modelItems", &modelItems);
}


void QMLHandler::refreshCurrentList(int currentListIndex, int groupId){
    //qDebug()<<"!!pozvan refreshaj listu "<<currentListIndex << "groupid "<<groupId;

    //currentDisplayedListIndex=currentListIndex;

    database->ispisiSveNaPopisima();

    modelList.clear();

    int currentListId=listAllLists[currentListIndex].dajId();

    std::vector<ElementPopisa> listElements=database->dajSveElementePopisa(currentListId);

    int idProsleGrupe=-1;
    int idTrenutneGrupe;
    int rbrGrupe=0;
    int index=0;

    for (unsigned int i=0; i<listElements.size(); i++){
        ElementPopisa elementPopisa=listElements.at(i);

        idTrenutneGrupe=elementPopisa.dajArtikl().dajGrupu().dajId();

        bool dodaj=(groupId==-1||groupId==idTrenutneGrupe);

        if (idTrenutneGrupe!=idProsleGrupe){
            rbrGrupe++;
            if (dodaj){
                modelList.addListItem(elementPopisa, true, rbrGrupe, index);
                index++;
            }
            if (dodaj){
                modelList.addListItem(elementPopisa, false, rbrGrupe, index);
                index++;
            }
            idProsleGrupe=idTrenutneGrupe;
        }
        else{
            if (dodaj){
                modelList.addListItem(elementPopisa, false, rbrGrupe, index);
                index++;
            }
        }
    }

    ctxt->setContextProperty("modelList", &modelList);
}

void QMLHandler::refreshUnits(){
    modelUnits.clear();

    modelUnits.addGroup(Grupa(0, "kom", -1), -1);
    modelUnits.addGroup(Grupa(1, "kg", -1), -1);
    modelUnits.addGroup(Grupa(2, "l", -1), -1);

    ctxt->setContextProperty("modelUnits", &modelUnits);
}

void QMLHandler::viewList_SetBought(int itemId, int listIndex, bool bought){
    //qDebug()<<"itemid"<<itemId<<"listid "<<listIndex<<"bought"<<bought;
    database->postaviKupljenArtiklPopis(itemId, listAllLists.at(listIndex).dajId(), bought);
}

void QMLHandler::viewList_DeleteBought(int listIndex, int groupId)
{
    int listId = listAllLists.at(listIndex).dajId();
    for (int i = 0; i < modelList.count(); i++)
    {
        if (modelList.get(i)->isBought())
            database->brisiArtiklPopis(modelList.get(i)->itemId(), listId);
    }
    refreshCurrentList(listIndex, groupId);
}



bool QMLHandler::editGroups_Add(QString name)
{
    if (database->postojiGrupa(name) != -1){
        return false;
    }else{
        //promijenimo prioritete grupa na njihov redni broj u listi
        for(int i = 0; i < modelGroupsWithoutAllGroups.count(); i++){
            database->postaviPrioritetGrupa(modelGroupsWithoutAllGroups.get(i)->groupId(), i+1);
        }

        //dodamo novi popis s prioritetom 0
        database->dodajGrupa(name);
        refreshGroups();

        return true;
    }
}

void QMLHandler::editGroups_Delete(int groupId)
{
    database->brisiGrupa(groupId);
    refreshGroups();
}

void QMLHandler::editGroups_ChangePriority(int index_1, int index_2)
{
    int id1 = modelGroupsWithoutAllGroups.get(index_1)->groupId();
    int id2 = modelGroupsWithoutAllGroups.get(index_2)->groupId();

    int pr1 = modelGroupsWithoutAllGroups.get(index_1)->groupPriority();
    int pr2 = modelGroupsWithoutAllGroups.get(index_2)->groupPriority();

    qDebug()<<id1 << " " << id2 << " " << pr1 << " " << pr2;

    database->postaviPrioritetGrupa(id1, pr2);
    database->postaviPrioritetGrupa(id2, pr1);

    refreshGroups();
}

bool QMLHandler::editGroups_Rename(QString name, int groupId)
{
    if (database->postojiGrupa(name) != -1){
        return false;
    }else{
        database->preimenujGrupa(groupId, name);
        return true;
    }
}

bool QMLHandler::firstTime(){
    return database->jePrvoPokretanje();
}

void QMLHandler::createTables(){
    database->napraviTablice();
}

void QMLHandler::createExampleDatabase(){
    database->napraviPrimjerBaze();
}

void QMLHandler::viewList_Delete(int listIndex, int itemId, int groupId){
    int listId=listAllLists[listIndex].dajId();

    database->brisiArtiklPopis(itemId, listId);
    refreshCurrentList(listIndex, groupId);
}

void QMLHandler::viewList_SetQuantity(int listIndex, int itemId, float quantity, QString unit){
    int listId=listAllLists[listIndex].dajId();

    database->izmjenaArtiklPopis(itemId, listId, quantity, unit);
}

bool QMLHandler::editItems_Add(QString name, int groupIdItem, int groupIndexRefresh)
{
    int groupIdRefresh = modelGroups.get(groupIndexRefresh)->groupId();
    if (database->postojiArtiklBazaIme(name) != -1){
        return false;
    } else {
        database->dodajArtiklBaza(name, groupIdItem, "");
        refreshItems(groupIdRefresh,-1);
        return true;
    }
}

void QMLHandler::editItems_Delete(int itemId, int groupIndex){
    int groupId = modelGroups.get(groupIndex)->groupId();
    database->brisiArtiklBaza(itemId);
    refreshItems(groupId,-1);
}

bool QMLHandler::editItems_Rename(QString name, int itemId){
    if (database->postojiArtiklBazaIme(name) != -1){
        return false;
    } else {
        database->preimenujArtikl(itemId, name);
        return true;
    }
}

void QMLHandler::editItems_ChangeGroup(int itemId, int newGroupId, int groupIndexRefresh){
    int groupIdRefresh = modelGroups.get(groupIndexRefresh)->groupId();
    database->prebaciArtiklBaza(itemId, newGroupId);
    refreshItems(groupIdRefresh,-1);
}

void QMLHandler::addItem_Add(int itemId, int listIndex, float quantity, QString unit, int groupIndexRefresh){
    database->dodajArtiklPopis(itemId, listAllLists.at(listIndex).dajId(), quantity, unit);
    refreshItems(groupIndexRefresh, listIndex);

}

bool QMLHandler::addItem_ExistItem(QString name, int listIndex){
    if (database->postojiArtiklPopisIme(name, listAllLists.at(listIndex).dajId()) != -1)
        return true;
    return false;
}
